## coding:utf-8
import numpy as np
from scipy.sparse import csr_matrix

###
def getDateInfo():
    import datetime
    now = datetime.datetime.now()
    return now

### dense away
def convertSparse2List(sparseVector):
    array = sparseVector.toarray()[0]  ## type ndarray
    lla = array.tolist()
    return lla

def getL2Dense(diffSparseVector):
    ## verify dense
    denseDSV = np.array(convertSparse2List(diffSparseVector))
    tempDense = denseDSV.dot(denseDSV)
    return np.sqrt(tempDense)

###convert csr_matrix vector to a ndarray, and compute L2
def getL2ViaNorm(diffSparseVector):
    from scipy.sparse.linalg import norm
    denseDSV = np.array(convertSparse2List(diffSparseVector))
    tempDense = norm(csr_matrix(denseDSV))
    return np.sqrt(tempDense)

def getL2SparseConcise(diffSparseVector):
    temp = csr_matrix.multiply(diffSparseVector, diffSparseVector)
    L2 = temp.sum(axis=1).tolist()[0][0]
    return np.sqrt(L2)

def generateHugeCSRVector(N):
    row = np.array([0, 0, 0, 0, 0, 0])
    col = np.array([0, 2, 2, 100, 111, 2000])
    data = np.array([1, 2, 3, 4, 5, 6])
    ll = csr_matrix((data, (row, col)), shape=(1, N))
    print "type:", type(ll), "shape:", ll.get_shape()
    return ll

### evaluate the difference between dense and sparse operation
def testHugeVector():
    N = 100000
    csrE = generateHugeCSRVector(N)
    ## **** sparse implementation *****8
    begin = getDateInfo()
    print "begin sparse:", begin
    L2 = getL2SparseConcise(csrE)
    print "sparseL2:", L2, np.sqrt(L2)

    end = getDateInfo()
    print "end sparse:", end
    print "diff:", end - begin
    ###*** dense implementation *****
    dBegin = getDateInfo()
    print "begin　dense:", dBegin
    denseL2 = getL2Dense(csrE)
    print "denseL2:", denseL2
    dEnd = getDateInfo()

    print "end dense:", dEnd
    print "diff:", dEnd - dBegin

    ###******* norm implementation ******
    normBegin = getDateInfo()
    print "begin　norm:", normBegin
    normL2 = getL2ViaNorm(csrE)
    print "denseL2:", normL2
    normEnd = getDateInfo()

    print "end dense:", dEnd
    print "diff:", dEnd - dBegin

if __name__ == "__main__":
    testHugeVector()